package com.untour.im.client;

import com.untour.im.client.command.ClientActionCommand;
import com.untour.im.client.handler.*;
import com.untour.im.client.listener.ClientChannelFutureListener;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Scanner;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class ClientArtisan {
    public static final int num = 5;

    public static void start(Integer clientType){
        AtomicInteger maxReconnectAttempts = new AtomicInteger(num);
        AtomicBoolean forceOffline = new AtomicBoolean(false);
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        bootstrap.group(group)
                .remoteAddress("127.0.0.1", 8899)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) {
                        ch.pipeline().addLast(new ClientIdleStateHandler());
                        ch.pipeline().addLast(new ClientChannelDuplexHandler());
                        ch.pipeline().addLast(new ServerResponseMessageDecoderHandler());
                        ch.pipeline().addLast(new ServerResponseMessageHandler());
//                        ch.pipeline().addLast(new OfflineServerResponseMessageHandler(forceOffline));
                        ch.pipeline().addLast(new RequestMessageEncoderHandler(clientType));
                        ch.pipeline().addLast(new ClientHeartBeatHandler(bootstrap,group,maxReconnectAttempts,forceOffline));
                    }
                });

        connect(bootstrap,group,maxReconnectAttempts,forceOffline);
    }

    public static void connect(Bootstrap bootstrap, NioEventLoopGroup group,
                               AtomicInteger maxReconnectAttempts,
                               AtomicBoolean forceOffline) {
        bootstrap.connect().addListener(new ClientChannelFutureListener());
    }

    public static void sendActionCommand(Channel channel) {
        // 直接采用控制台输入的方式，模拟操作指令
        Scanner scanner = new Scanner(System.in);
        ClientActionCommand command = new ClientActionCommand();
        new Thread(() -> {
            // 此处循环等待客户端输入
            while (!Thread.interrupted()) {
                //  后去获取指令
                command.exec(scanner,channel);
            }
        }).start();
    }

}
